import router from '@/router'
// @ts-ignore
import nprogress from 'nprogress'
import { ElMessage } from 'element-plus'
import 'nprogress/nprogress.css'
import pinia from './store'
import useUserStore from './store/modules/user'
import setting from './setting'
let userStore = useUserStore(pinia)

nprogress.configure({ showSpinner: false })

router.beforeEach((to: any, _from: any, next: any) => {
  // 未登录时，除了login 其他都不可访问
  // 已登录时，除了login 其他都可以访问
  document.title = `${setting.title}-${to.meta.title}`
  let token = userStore.token
  let username = userStore.username
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        // 获取用户信息
        userStore
          .userInfo()
          .then(() => {
            next({...to})
          })
          .catch(() => {
            userStore
              .userLogout()
              .then(() => {
                next({
                  path: '/login',
                  query: {
                    redirect: to.path,
                  },
                })
              })
              .catch((err) => {
                ElMessage({
                  type: 'error',
                  message: err,
                })
              })
          })
      }
    }
  } else {
    if (to.path != '/login') {
      next({ path: '/login', query: { redirect: to.path } })
    } else {
      next()
    }
  }
  nprogress.start()
})

router.afterEach(() => {
  nprogress.done()
})
